from django.db import models
from django.contrib.auth.models import User


class Survey(models.Model):
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('closed', '已关闭')
    ]

    name = models.CharField('问卷标题', max_length=255, blank=True)
    description = models.TextField('问卷描述', blank=True)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建者')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='draft')

    class Meta:
        verbose_name = '问卷'
        verbose_name_plural = '问卷管理'

    def __str__(self):
        return self.name


class Question(models.Model):
    TYPE_CHOICES = [
        ('single', '单选题'),
        ('multiple', '多选题'),
        ('text', '文本题')
    ]

    survey = models.ForeignKey(Survey, on_delete=models.CASCADE, related_name='questions')
    text = models.TextField('问题内容', blank=True)
    type = models.CharField('题型', max_length=20, choices=TYPE_CHOICES)
    order = models.PositiveIntegerField('排序', default=0)
    required = models.BooleanField('必填', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        ordering = ['order']
        verbose_name = '问题'
        verbose_name_plural = '问题管理'

    def __str__(self):
        return f"{self.get_type_display()} - {self.text[:50]}"


class Option(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options')
    text = models.CharField('选项内容', max_length=500)
    order = models.PositiveIntegerField('排序', default=0)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        ordering = ['order']
        verbose_name = '选项'
        verbose_name_plural = '选项管理'

    def __str__(self):
        return self.text[:50]

class Answer(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Answer to {self.question.text} by {self.user.username}"



# 扩展用户模型，添加安全问题和答案
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    security_question = models.CharField('安全问题', max_length=255)
    security_answer = models.CharField('安全答案', max_length=255)  # 将在保存时加密

    def __str__(self):
        return f"{self.user.username} - {self.security_question}"